package com.example.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.jwt.JwtHelper;
import com.example.common.md5.MD5;
import com.example.common.util.Result;
import com.example.dto.system.LoginDto;
import com.example.system.SysUser;
import com.example.system.service.impl.SysUserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "后台登录管理")
@RestController
@RequestMapping("admin/system/index")
public class LoginController {

    @Autowired
    private SysUserServiceImpl sysUserService;

    /**
     * 登录
     * @return
     */
    @ApiOperation(value = "登录")
    @PostMapping("login")
    public Result login(@RequestBody LoginDto loginDto){
//        System.out.println("login");
        if(loginDto == null){
            return Result.build(null,201,"用户名和密码为空");
        }
        //根据用户名查找用户
        String username = loginDto.getUsername();
//        SysUser user = sysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername,username);
        SysUser user = sysUserService.getOne(wrapper);
//        System.out.println("user==="+user);
//        System.out.println("username==="+username);
        if(user == null){
            return Result.build(null,201,"用户不存在");
        }

        //判断密码是否相同
        String dbPassword = user.getPassword();
        String dtoPassword = MD5.encrypt(loginDto.getPassword());
        if(!dtoPassword.equals(dbPassword)){
            return Result.fail("密码错误");
        }

//        1 可用 0 禁用
        if(user.getStatus() == 0){
            Result.fail("该用户已被禁用");
        }

//       使用jwt根据用户id和用户名称生成token字符串
        String token = JwtHelper.createToken(user.getId(), user.getUsername());
        Map<String,String> map = new HashMap<>();
        map.put("token",token);
        return Result.ok(map);
    }

    /**
     * 获取用户信息
     * @return
     */
    @ApiOperation("获取用户信息")
    @GetMapping("info")
    public Result info(HttpServletRequest request){
        String username = JwtHelper.getUsername(request.getHeader("token"));
        Map<String,Object> map = sysUserService.getUserInfo(username);
        return Result.ok(map);
    }

    /**
     * 退出
     * @return
     */
    @PostMapping("logout")
    public Result logout(){
        return Result.ok();
    }

}
